package com.ruoyi.ai.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.io.FileUtil;
import com.ruoyi.ai.api.bo.WxChatMessageBo;
import com.ruoyi.ai.api.bo.WxMaChatQueryBo;
import com.ruoyi.ai.domain.bo.WxChatBo;
import com.ruoyi.ai.domain.bo.WxDialogueBo;
import com.ruoyi.ai.domain.vo.WxChatVo;
import com.ruoyi.ai.domain.vo.WxDialogueVo;
import com.ruoyi.ai.service.IFileService;
import com.ruoyi.ai.service.IWxChatService;
import com.ruoyi.ai.service.IWxDialogueService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai/webChat")
public class WebChatController extends BaseController {
    private final IWxChatService iWxChatService;
    private final IWxDialogueService iWxDialogueService;
    private final ISysUserService sysUserService;
    private final IFileService fileService;

    /**
     * 网页聊天
     */
    @SaCheckPermission("ai:web:chat")
    @PostMapping("/chat")
    public R<Void> chat(@RequestBody WxChatMessageBo chatMessageBo) {
        iWxChatService.chat(chatMessageBo);
        return R.ok();
    }

    @SaCheckPermission("ai:web:chat")
    @GetMapping("/getChatNum")
    public R<Integer> getChatNum() {
        Long userId = LoginHelper.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        return R.ok(sysUser.getChatNum());
    }

    /**
     * 创建新对话
     */
    @SaCheckPermission("ai:web:chat")
    @PostMapping("/createDialogue")
    @RepeatSubmit()
    public R<Long> createDialogue() {
        WxDialogueBo bo = new WxDialogueBo();
        bo.setWxUserId(LoginHelper.getUserId());
        bo.setFirstContent("");
        bo.setIsShow(true);
        bo.setUserType(UserType.SYS_USER.getUserType());
        boolean result = iWxDialogueService.insertByBo(bo);
        return result ? R.ok(bo.getDialogueId()) : R.fail("创建对话失败");
    }

    /**
     * 获取聊天历史
     */
    @SaCheckPermission("ai:web:chat")
    @PostMapping("/history")
    public R<List<WxChatVo>> getChatHistory(@RequestBody WxMaChatQueryBo queryBo) {
        WxChatBo bo = new WxChatBo();
        bo.setDialogueId(queryBo.getDialogueId());
        Map<String, Object> params = bo.getParams();
        params.put("orderBySort", "asc");
        return R.ok(iWxChatService.queryList(bo));
    }

    /**
     * 查询对话列表
     */
    @SaCheckPermission("ai:web:chat")
    @GetMapping("/dialogueList")
    public TableDataInfo<WxDialogueVo> listDialogues(WxDialogueBo bo, PageQuery pageQuery) {
        bo.setWxUserId(LoginHelper.getUserId());
        bo.setIsShow(true);
        bo.setUserType(UserType.SYS_USER.getUserType());
        return iWxDialogueService.queryPageList(bo, pageQuery);
    }

    /**
     * 删除对话
     * 实际上没删除，只是把isShow改成false
     */
    @SaCheckPermission("ai:web:chat")
    @Log(title = "对话", businessType = BusinessType.DELETE)
    @PostMapping("/deleteDialogue/{dialogueId}")
    public R<Void> notShow(@NotNull(message = "主键不能为空")
                           @PathVariable Long dialogueId) {
        Boolean b = iWxDialogueService.notShow(Collections.singletonList(dialogueId));
        return R.ok();
    }
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, Object>> avatar(@RequestPart("avatarfile") MultipartFile avatarfile) {
        Map<String, Object> ajax = new HashMap<>();
        if (!avatarfile.isEmpty()) {
            String extension = FileUtil.extName(avatarfile.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            Map<String, String> upload = fileService.uploadFileLocal(avatarfile);
            String avatar = upload.get("url");
            if (sysUserService.updateUserAvatar(getUsername(), avatar)) {
                ajax.put("imgUrl", avatar);
                return R.ok(ajax);
            }
        }
        return R.fail("上传图片异常，请联系管理员");
    }
}
